package cn.com.homeyoda.aimate.aihealth.ui.videoinspect;

import static com.wzq.mvvmsmart.utils.Utils.getContext;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProviders;

import com.wzq.mvvmsmart.utils.EncodeUtils;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;
import com.wzq.mvvmsmart.utils.ImageUtils;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.ExaminationReportDetailsBean;
import cn.com.homeyoda.aimate.aihealth.bean.FaceInfoBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityDetectionResultBinding;
import cn.com.homeyoda.aimate.aihealth.ui.my.MyActivity;
import cn.com.homeyoda.aimate.aihealth.utils.BindUserDialog;
import cn.com.homeyoda.aimate.aihealth.utils.ImageUtil;
import cn.com.homeyoda.aimate.aihealth.utils.ShowXiaZaiDialog;

//检测结果
public class DetectionResultActivity extends BaseActivity<ActivityDetectionResultBinding, VideoInspectModel>{
    String reportId = "";//检测报告id
    String faceId = "";

    String downloadQrCode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public VideoInspectModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(VideoInspectModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        Log.i("huazai","DetectionResultActivity===");
        try {
            reportId = getIntent().getStringExtra("reportId");
            faceId = getIntent().getStringExtra("faceId");
            Log.i("huage","reportId==="+reportId);
            Log.i("huage","faceId==="+faceId);
        }catch (NullPointerException exception){

        }

        initView();
        viewModel.faceInfo(faceId);
        viewModel.examinationReportDeta(reportId);
    }

    private void initView() {


        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.chakan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin()) {
                    startLoginActivity();
                }else{
                    startActivity(new Intent(getContext(), MyActivity.class));
                    finish();
                }

            }
        });

        binding.bindbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.getBindUser(Build.SERIAL);
//                if (!isLogin()) {
//                    startLoginActivity();
//                }else{
//                    viewModel.getBindUser(Build.SERIAL);
//                }

            }
        });


    }

    @Override
    public void initViewObservable() {
        viewModel.stateReportData.observe(this,examinationReportDetailsBean -> {
            setData(examinationReportDetailsBean);
        });
        viewModel.faceInfoData.observe(this,faceInfoBean -> {
            if (faceInfoBean == null || faceInfoBean.getData() == null) return;
//            if(faceInfoBean.getData().getIsBindUser().equals("0")){//未绑定
//                binding.bindbtn.setVisibility(View.VISIBLE);
//                binding.bindtip.setVisibility(View.VISIBLE);
//            }else{
//                binding.bindbtn.setVisibility(View.GONE);
//                binding.bindtip.setVisibility(View.GONE);
//            }
            binding.bindbtn.setVisibility(View.GONE);
            binding.bindtip.setVisibility(View.GONE);
            if(faceInfoBean.getData().getIsJoinFamily()==null){
                binding.jiaTip.setVisibility(View.VISIBLE);
            }else{
                if(faceInfoBean.getData().getIsJoinFamily().equals("1")){//已加入家庭
                    binding.jiaTip.setVisibility(View.GONE);
                }else{//未加入
                    binding.jiaTip.setVisibility(View.VISIBLE);
                }
            }

            setInfoData(faceInfoBean.getData());
        });
        viewModel.bindUserData.observe(this,bindUserQrCode -> {
            byte[] bytes = EncodeUtils.base64Decode(bindUserQrCode.getMsg());
            Bitmap bitmap = ImageUtils.bytes2Bitmap(bytes);
//            Bitmap bitmap = ImageUtil.base64ToBitmap(bindUserQrCode.getMsg());
            BindUserDialog bindUserDialog = new BindUserDialog(this,bitmap,"请扫码进行绑定!");
            bindUserDialog.Show();
        });
    }

    private void setInfoData(FaceInfoBean.DataBean data){
        String name = data.getName();
        String sex = data.getSex();
        String age = data.getAge();
        String height = data.getHeight();
        String weight = data.getWeight();
        String avatar = data.getAvatar();
        Log.i("huage","getAvater====="+avatar);
        GlideLoadUtils.loadCircleImg(this,R.mipmap.tou_bg,binding.head,avatar);
        if(height != null){
            binding.height.setText(height+"CM");
        }else {
            binding.height.setVisibility(View.GONE);
            binding.height1.setVisibility(View.GONE);
        }
        if(weight != null){
            binding.weight.setText(weight+"KG");
        }else {
            binding.weight.setVisibility(View.GONE);
            binding.weight1.setVisibility(View.GONE);
        }
        if(age != null){
            binding.age.setText(age+"岁");
        }else{
            binding.age.setVisibility(View.GONE);
        }
        if(name != null){
            String result = name.replace("\n", "");
            binding.name.setText(result);
        }else{
            binding.name.setVisibility(View.GONE);
        }
        if(sex.equals("0")){
            binding.sex.setText("未设置");
        }else if(sex.equals("1")){
            binding.sex.setText("男");
        }else if(sex.equals("2")){
            binding.sex.setText("女");
        }
    }

    private void setData(ExaminationReportDetailsBean examinationReportDetailsBean){

        String addTime = examinationReportDetailsBean.getData().getAddTime();
        String conclusion = examinationReportDetailsBean.getData().getConclusion();

        String fenshu  = examinationReportDetailsBean.getData().getScore();
        String baogao = examinationReportDetailsBean.getData().getRemark();
        downloadQrCode = examinationReportDetailsBean.getData().getDownloadQrCode();


        if(fenshu != null){
            binding.fenshu.setText(fenshu);
            if(Integer.parseInt(fenshu) <= 60){
                binding.pingfen.setBackgroundResource(R.mipmap.pingfen_di);
            }else if(Integer.parseInt(fenshu) > 60 && Integer.parseInt(fenshu) < 90){
                binding.pingfen.setBackgroundResource(R.mipmap.pingfen);
            }else if(Integer.parseInt(fenshu) >= 90){
                binding.pingfen.setBackgroundResource(R.mipmap.pingfen_gao);
            }
        }
        if(baogao != null){
            String cleanedText = baogao.replaceFirst("^\\n", "");
            binding.baogao.setText(cleanedText);
        }

        if(addTime != null){
            binding.addtime.setText("测量时间: "+addTime.split(" ")[0]);
        }
        if(conclusion != null){
            binding.conclusion.setText(conclusion);
        }
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) binding.shuzhangIcon.getLayoutParams();
        ViewGroup.MarginLayoutParams params2 = (ViewGroup.MarginLayoutParams) binding.shousuoIcon.getLayoutParams();
        for(ExaminationReportDetailsBean.DataBean.TextDescriptionBean textDescriptionBean : examinationReportDetailsBean.getData().getTextDescription()){
            if(textDescriptionBean.getName().equals("心率")){
                binding.xinlv.setText(textDescriptionBean.getValue());
            }
            if(textDescriptionBean.getName().equals("呼吸")){
                binding.huxi.setText(textDescriptionBean.getValue());
            }
            if(textDescriptionBean.getName().equals("血氧")){
                binding.xueyang.setText(textDescriptionBean.getValue());
            }
            if(textDescriptionBean.getName().equals("收缩压")){
                int value = Integer.parseInt(textDescriptionBean.getValue());
                binding.shousuo.setText(textDescriptionBean.getValue());
                int max = Integer.parseInt(textDescriptionBean.getValueMax());
                int min = Integer.parseInt(textDescriptionBean.getValueMin());
                if(value > max){
                    binding.shousuo.setTextColor(getContext().getResources().getColor(R.color.red));
                    binding.shousuoIcon.setVisibility(View.VISIBLE);
                    binding.shousuoIcon.setBackgroundResource(R.mipmap.shang);
                    int marginTopInPx = dpToPx(10, this);
                    params.topMargin = marginTopInPx;
                    binding.shousuoIcon.setLayoutParams(params);

                }
                if(value < min){
                    binding.shousuo.setTextColor(getContext().getResources().getColor(R.color.c_2cb176));
                    binding.shousuoIcon.setVisibility(View.VISIBLE);
                    binding.shousuoIcon.setBackgroundResource(R.mipmap.xia);
                    int marginTopInPx = dpToPx(20, this);
                    params.topMargin = marginTopInPx;
                    binding.shousuoIcon.setLayoutParams(params);
                }
                if (value >= min && value <= max) {
                    binding.shousuo.setTextColor(getContext().getResources().getColor(R.color.black));
                    binding.shousuoIcon.setVisibility(View.GONE);
                }
            }
            if(textDescriptionBean.getName().equals("舒张压")){
                binding.shuzhang.setText(textDescriptionBean.getValue());
                int value = Integer.parseInt(textDescriptionBean.getValue());
                binding.shuzhang.setText(textDescriptionBean.getValue());
                int max = Integer.parseInt(textDescriptionBean.getValueMax());
                int min = Integer.parseInt(textDescriptionBean.getValueMin());
                if(value > max){
                    binding.shuzhang.setTextColor(getContext().getResources().getColor(R.color.red));
                    binding.shuzhangIcon.setVisibility(View.VISIBLE);
                    binding.shuzhangIcon.setBackgroundResource(R.mipmap.shang);
                    int marginTopInPx = dpToPx(10, this);
                    params.topMargin = marginTopInPx;
                    binding.shuzhangIcon.setLayoutParams(params);
                }
                if(value < min){
                    binding.shuzhang.setTextColor(getContext().getResources().getColor(R.color.c_2cb176));
                    binding.shuzhangIcon.setVisibility(View.VISIBLE);
                    binding.shuzhangIcon.setBackgroundResource(R.mipmap.xia);
                    int marginTopInPx = dpToPx(20, this);
                    params.topMargin = marginTopInPx;
                    binding.shuzhangIcon.setLayoutParams(params);
                }
                if (value >= min && value <= max) {
                    binding.shuzhang.setTextColor(getContext().getResources().getColor(R.color.black));
                    binding.shuzhangIcon.setVisibility(View.GONE);
                }
            }
            if(textDescriptionBean.getName().equals("年龄段")){
                binding.nianlingduan.setText(textDescriptionBean.getValue());
            }
        }

        binding.xiazai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("huahua","xiazai========");
                if(downloadQrCode.equals("")){
                    Toast.makeText(getContext(),"没有可下载的报告",Toast.LENGTH_SHORT).show();
                }else{
                    showDialog(downloadQrCode);
                }
            }
        });


    }

    private void showDialog(String imgUrl){
        ShowXiaZaiDialog showXiaZaiDialog = new ShowXiaZaiDialog(this,imgUrl);
        showXiaZaiDialog.Show();
    }

    public static int dpToPx(int dp, Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f); // 四舍五入
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }





    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_detection_result;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
